import React, { Component } from 'react';
import { Col, Row, Card, Button, Modal, message, Tooltip, Select } from 'antd';
import { connect } from 'dva';
import style from '../base.less';
import RadiosTable from '../components/radiosTable';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import {  ExclamationCircleOutlined } from '@ant-design/icons';
import LayerModel from '../components/layerModel';
import moment from 'moment';

const mapStateToProps = (state: any) => {
  return {
    loading: state.loading.effects['modelConfig/getFetchPage'],
    permissions: state?.menu?.permissions,
    rightList: state?.modelConfig?.pageData,
  };
};

class index extends Component<any> {
  state = {
    leftList: [],
    rightTitle: '',
    rightQuery: {},
    rightKey:"",
    brandOptions: [],
    defaultBrand: '',
    selectBrand: ''
  };
  tableRef = null;
  leftLayerRef = React.createRef();
  rightLayerRef = React.createRef();
  layerRightColumns = [
    {
      type: 'input',
      formItem: {
        name: 'name',
        label: '数据类别',
        rules: [{ required: true, message: '请输入数据类别' }],
      },
      label: {
        placeholder: '请输入数据类别',
        disabled:true,
      },
    },
    {
      type: 'input',
      formItem: {
        name: 'key',
        label: 'KEY值',
        rules: [{ required: true, message: '请输入KEY值' }],
      },
      label: {
        placeholder: '请输入KEY值',
        disabled:true,
      },
    },
    {
      type: 'textArea',
      formItem: {
        name: 'remark',
        label: '备注',
      },
      label: {
        placeholder: '请输入备注',
        disabled:true,
      },
    },
  ];
  tableQueryUrl = {
    type: 'modelConfig/getFetchPage',
    url: '/msdevice/base/data/page',
  };

  componentDidMount() {
    const { dispatch } = this.props;
    let brandCode = '';
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res:any) => {
        this.setState({ 
           brandOptions: res?.data,
           defaultBrand: res?.data[0].brandCode,
           selectBrand: res?.data[0].brandCode
          });
          this.initData(res?.data[0].brandCode);
        }
    });
    // this.initData(brandCode);
  }
  initData = async (value:any) => {
    // 获取左侧数据
    const res = await this.leftGetList(value);
    // 如果数据大于0
    // 默认选中第一个
    this.setOneSelect(res);
  };
  setOneSelect = res => {
    this.tableRef?.setIndex(res[0]?.sid || '');
    if (res && res.length > 0) {
      // 执行右侧数据
      this.rightGetList({ ...res[0] });
    }
  };

  // 左侧获取数据
  leftGetList = (value:any) => {
    const { dispatch } = this.props;
    const {selectBrand}=this.state;
    let brandCode = '';
    if(value){
      brandCode = value;
    }else{
      brandCode = selectBrand;
    }
    return new Promise(resolve => {
      dispatch({
        type: 'modelConfig/getData',
        payload: { url: '/msdevice/base/data/type/list', brandCode: brandCode },
        callback: res => {
          this.setState({
            leftList: res.data,
          });
          resolve(res.data);
        },
      });
    });
  };
  // 右侧获取数据
  rightGetList = (obj = {}) => {
    const { rightQuery, rightTitle,rightKey } = this.state;
    const { sid } = obj;
    const params = sid
      ? {
          typeId: sid,
          key: '',
          name: '',
        }
      : rightQuery;
    this.setState({
      rightQuery: params,
      rightTitle: obj.typeName || rightTitle,
      rightKey:obj.typeKey || rightKey
    });
    const { dispatch } = this.props;
    dispatch({
      type: this.tableQueryUrl.type,
      payload: { url: this.tableQueryUrl.url, ...params },
    });
  };
  // 左侧删除
  leftDelete = (record: any, close: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'modelConfig/postObjWithRes',
      payload: { url: `/msdevice/base/data/type/delete/${record.sid}` },
      callback: res => {
        // /{userId}
        // 关闭
        close();
        if (res.statusCode === '0') {
          // 刷新数据
          this.initData();
          // 提示
          message.success('删除成功');
        }
      },
    });
  };
  // 右侧删除
  rightDelete = (record, close) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'modelConfig/postObjWithRes',
      payload: { url: `/msdevice/base/data/delete/${record.sid}` },
      callback: res => {
        close();
        if (res.statusCode === '0') {
          // 刷新数据
          this.rightGetList();
          // 提示
          message.success('删除成功');
        }
      },
    });
  };
  // 提交
  leftOnchange = (obj, close) => {
    // 提交
    const { dispatch } = this.props;
    const { rightQuery } = this.state;
    const { sid, typeName, typeKey, location, brandCode } = obj;
    const params = {
      typeName,
      typeKey,
      brandCode,
      location: location[0] == location[1] ? `${location[0]}` : location.join('-'),
    };
    Object.assign(params, sid ? { sid } : {});
    const type = sid ? 'edit' : 'save';

    dispatch({
      type: 'modelConfig/postObjWithRes',
      payload: { url: `/msdevice/base/data/type/${type}`, ...params },
      callback: async res => {
        // 关闭
        close();
        if (res.statusCode === '0') {
          // 刷新数据
          const arr = await this.leftGetList();

          // 如果新增后只有一条数据的情况
          if (arr && arr.length === 1) {
            this.setOneSelect(arr);
          }
          // 提示
          message.success(`${sid ? '更新' : '新增'}成功`);
        }

        // 如果修改的和右侧表格一样修改右侧名字
        if (sid === rightQuery.typeId) {
          this.setState({
            rightTitle: typeName,
          });
        }
      },
    });
  };
  // 提交
  rightOnchange = async (obj, close) => {
    close();
    return 
    // 提交
    const { dispatch } = this.props;
    const { typeId } = this.state.rightQuery;
    const { sid, key, name, remark } = obj;
    const params = {
      key,
      name,
      remark,
    };
    Object.assign(
      params,
      sid
        ? {
            sid,
          }
        : {
            typeId,
          },
    );
    const type = sid ? 'edit' : 'save';
    dispatch({
      type: 'modelConfig/postObjWithRes',
      payload: { url: `/msdevice/base/data/${type}`, ...params },
      callback: res => {
        // 关闭
        close();

        if (res.statusCode === '0') {
          // 刷新数据
          this.rightGetList();
          // 提示
          message.success(`${sid ? '更新' : '新增'}成功`);
        }
      },
    });
  };

  rightNewAdd = () => {
    const { rightTitle } = this.state;
    this.setLabelFn(rightTitle);
    this.rightLayerRef?.current?.setInitVal(`新增${rightTitle}`);
  };
  setLabelFn = (rightTitle: string) => {
    const str = `请输入${rightTitle}`;
    this.layerRightColumns[0].formItem.label = rightTitle;
    this.layerRightColumns[0].formItem.rules[0].message = str;
    this.layerRightColumns[0].label.placeholder = str;
  };
  
  onBrandSelect = (value:any) =>{
    this.setState({
      selectBrand: value
    })
    this.leftGetList(value);
  }
  render() {
    const { leftList, rightTitle, rightQuery,rightKey,brandOptions,defaultBrand } = this.state;

    const {
      loading,
      location: { pathname = '/' },
      rightList: { list, pagination },
      permissions,
    } = this.props;

    // 左侧表格
    const tableProps = {
      onRef: ref => {
        this.tableRef = ref;
      },
      scroll: { x: 300, y: 650 },
      menu: [
        {
          name: '编辑',
          auth: 'modelConfig_edit',
          onClick: (record: any) => {
            const { location } = record;
            const locationArr =
              location.length > 1 ? record.location.split('-') : [location, location];
            // 打开弹层传值
            this.leftLayerRef?.current?.setInitVal('编辑数据类别', {
              ...record,
              location: locationArr,
            });
          },
        },
        {
          name: '删除',
          auth: 'modelConfig_delete',
          onClick: (record: any) => {
            let confirmLoading = false;
            Modal.confirm({
              title: '删除',
              content: (
                <>
                  <p>确定要删除当前数据类别吗？</p>
                  <p>删除后，当前数据类别下的所有数据都将被删除。</p>
                </>
              ),
              wrapClassName: 'layer-model-box',
              icon: <ExclamationCircleOutlined />,
              onOk: async close => {
                // 如果为重复点击
                if (confirmLoading) {
                  return false;
                }
                confirmLoading = true;
                // 点击删除请求接口
                await this.leftDelete(record, close);
              },
            });
          },
        },
      ],
      columns: [
        {
          title: '数据类别名称',
          dataIndex: 'typeName',
          //   ellipsis: {
          //     showTitle: false,
          //   },
          render(text: string) {
            return (
              <Tooltip placement="topLeft" title={text}>
                <div
                  style={{
                    whiteSpace: 'nowrap',
                    width: '100px',
                    textOverflow: 'ellipsis',
                    overflow: 'hidden',
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            );
          },
          //   width:"110px",
        },
        {
          title: 'KEY值',
          dataIndex: 'typeKey',
          render(text: string) {
            return (
              <Tooltip placement="topLeft" title={text}>
                <div
                  style={{
                    whiteSpace: 'nowrap',
                    width: '80px',
                    textOverflow: 'ellipsis',
                    overflow: 'hidden',
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            );
          },
          //   width:"80px",
        },
        {
          title: '编码位置',
          dataIndex: 'location',
          //   width:"80px",
        },
      ],
      keyName: 'sid',
      list: leftList,
      title: {
        name: '数据类别',
        auth: 'modelConfig_add',
        onClick: () => {
          this.leftLayerRef?.current?.setInitVal('新增数据类别', {
            location: [8, 14],
          });
        },
      },
      onRow: row => {
        this.rightGetList({ ...row });
      },
      scroll: { x: '100%' },
    };
    
    // 右侧表格
    const searchItems = [
      {
        type: 'input',
        title: `${rightTitle}名称`,
        key: 'name',
      },
      {
        type: 'input',
        title: `KEY值`,
        key: 'key',
      },
    ];
    const total = pagination?.total || 0;
    const pageNo = pagination?.pageNo || 1;
    const num = Math.ceil(total / (pagination?.pageSize || 10));
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>
          共&nbsp;{total}&nbsp;条记录&nbsp;{pageNo}/{num}&nbsp;页
        </span>
      ),
    };
   
    
    const rightColumns = [
      {
        title: `${rightTitle}名称`,
        dataIndex: 'name',
      },
      {
        title: `KEY值`,
        dataIndex: 'oriKey',
      },
      {
        title: `备注`,
        dataIndex: 'remark',
      },
      {
        title: `创建时间`,
        dataIndex: 'createDate',
        render: (txt: string) => moment(txt).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        title: `操作`,
        dataIndex: '操作',
        fixed: 'right',
        width: 140,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看',
              key: 'edit',
              auth: 'modelConfig_edit',
              onConfirm: () => {
                this.setLabelFn(rightTitle);
                this.rightLayerRef?.current?.setInitVal(`查看${rightTitle}`, record);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'modelConfig_delete',
              // Popconfirm: true,
              // message: '是否确定删除？',
              onConfirm: () => {
                let confirmLoading = false;
                Modal.confirm({
                  title: '删除',
                  content: (
                    <>
                      <p>确定要删除当前{rightTitle}吗？</p>
                    </>
                  ),
                  wrapClassName: 'layer-model-box',
                  icon: <ExclamationCircleOutlined />,
                  onOk: close => {
                    // 如果为重复点击
                    if (confirmLoading) {
                      return false;
                    }
                    confirmLoading = true;
                    // 点击删除请求接口
                    this.rightDelete(record, close);
                  },
                });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];
    const isRightVehicleType = ['optional_package','body_color','change_package','interior_color'].find(e=>e===rightKey)
    if(isRightVehicleType){
        rightColumns.unshift( {
            title: `所属车型`,
            dataIndex: 'baseCode',
          })
    }
    const rightTable = {
      columns: rightColumns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const options = brandOptions.map((item:any)=>{
      return {
        label: item.brandName,
        value: item.brandCode
      }
    })
    const layerLeftColumns = [
      {
        type: 'select',
        formItem: {
          name: 'brandCode',
          label: '品牌',
          rules: [{ required: true, message: '请选择品牌' }],
        },
        label: {
          placeholder: '请输入数据类别',
        },
        options: options,
      },
      {
        type: 'input',
        formItem: {
          name: 'typeName',
          label: '数据类别',
          rules: [{ required: true, message: '请输入数据类别' }],
        },
        label: {
          placeholder: '请输入数据类别',
        },
      },
      {
        type: 'input',
        formItem: {
          name: 'typeKey',
          label: 'KEY值',
          rules: [{ required: true, message: '请输入KEY值' }],
        },
        label: {
          placeholder: '请输入KEY值',
        },
      },
      {
        type: 'slider',
        formItem: {
          name: 'location',
          label: '编码位置',
          rules: [{ required: true, message: '请选择编码位置' }],
        },
        label: {
          min: 1,
          max: 22,
          marks: { 1: 1, 22: 22 },
        },
      },
    ];

    return (
      <div>
        <Row gutter={24}>
        <div  style={{margin: '0px 10px 10px 10px'}}>
          <div style={{display:'inline-block'}}>
          <span>品牌：</span>
            </div>
            <div style={{display:'inline-block'}}>
                 <Select
                    allowClear={false}
                    placeholder="请选择品牌"
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    
                    onChange={this.onBrandSelect}
                    style={{width: '250px'}}
                    key={defaultBrand}
                    defaultValue={defaultBrand}
                    options={options}
                  >
                  </Select>
                  </div>
            </div>
        </Row>
        <Row gutter={24} className={style.baseData}>
          <Col span={8}>
            <RadiosTable {...tableProps}></RadiosTable>
          </Col>
          {leftList?.length > 0 && (
            <Col span={16}>
              <Card title={rightTitle}>
                <PateoSearchForm
                  searchItems={searchItems}
                  fetchParams={this.tableQueryUrl}
                  saveFormValues={(val: any) => {
                    this.setState({ rightQuery: { ...rightQuery, ...val } });
                  }}
                  handleFormReset={() => {
                    const { rightQuery } = this.state;
                    this.setState({ rightQuery: { typeId: rightQuery.typeId } });
                  }}
                  handleFieldsValue={fieldsValue => {
                    return { ...fieldsValue, typeId: rightQuery.typeId };
                  }}
                />
                {/* <div className="add-btn">
                  {permissions.includes(`${pathname}/modelConfig_add`) && (
                    <Button type="primary" onClick={this.rightNewAdd} icon={<PlusOutlined />}>
                      新增{rightTitle}
                    </Button>
                  )}
                </div> */}
                <div style={{paddingTop:"15px"}}></div>
                <PateoTable
                  extraHandle={true}
                  tableProps={rightTable}
                  fetchParams={this.tableQueryUrl}
                  formValues={rightQuery}
                  currentName="pageNo"
                />
              </Card>
            </Col>
          )}
        </Row>
        <LayerModel
          ref={this.leftLayerRef}
          onChange={this.leftOnchange}
          columns={layerLeftColumns}
        ></LayerModel>
        <LayerModel
          ref={this.rightLayerRef}
          onChange={this.rightOnchange}
          columns={this.layerRightColumns}
          width={600}
        ></LayerModel>
      </div>
    );
  }
}

export default connect(mapStateToProps)(index);
